package com.heima.common.threadlocal;

import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import lombok.extern.slf4j.Slf4j;

/**
 * 存放用户id的容器
 */
@Slf4j
public class UserThreadLocalUtils {

    private final static ThreadLocal<Integer> userThreadLocal = new ThreadLocal<>();

    /**
     * 获取线程中的用户
     *
     * @return
     */
    public static Integer getUserId() {
        return userThreadLocal.get();
    }

    /**
     * 获取线程中的用户并检测用户是否存在; 如果用户不存在, 抛出异常
     *
     * @return
     */
    public static Integer getUserIdAndCheckLogin() {
        Integer userId = userThreadLocal.get();
        if (userId == null) {
            log.error("线程空间获取userId不存在!");
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }
        return userId;
    }

    /**
     * 设置当前线程中的用户
     *
     * @param userId
     */
    public static void setUserId(Integer userId) {
        userThreadLocal.set(userId);
    }

    public static void removeUser() {
        userThreadLocal.remove();
    }

}
